<?php

namespace Account\Model;

use Common\Model\BaseModel;

class MessageBoxModel extends BaseModel {

    protected $_auto = [
        ['create_time', 'time', self::MODEL_INSERT, 'function'],
    ];
    protected $_validate = [
    ];
    protected $_scope = [
    ];

    /**
     * 检查全站新信件
     *
     * @return void
     */
    public function pickGlobalMessage($uid) {
        $hasIds = D('MessageBox')
                ->where(['user_id' => $uid])
                ->cache(60)
                ->getField('msg_id', true);
        $msgIds = D('Message')
                ->where("receive_id = {$uid} OR rec_type = 1")
                ->where(['delete_time' => 0])
                ->cache(60)
                ->getField('id', true);

        $hasIds = $hasIds ? : [];
        $msgIds = $msgIds ? : [];

        $diffIds = array_diff($msgIds, $hasIds);
        if ($diffIds) {
            $diffMessages = [];
            foreach ($diffIds as $diffId) {
                $diffMessages[] = [
                    'user_id' => $uid,
                    'msg_id' => $diffId,
                    'is_read' => 0,
                    'create_time' => time(),
                ];
            }
            D('MessageBox')->addAll($diffMessages);
            return true;
        }
        return FALSE;
    }

}
